import bulletinInsertOrUpdateApi from '@/api/bulletin/bulletinInsertOrUpdateApi'
import bulletinPageApi from '@/api/bulletin/bulletinPageApi'
import doDelDataClick from '@/api/common/delDataApi'
import notBlankIdApi from '@/api/common/notBlankIdApi'
import CSearchForm from '@/components/CSearchForm/CSearchForm'
import CTable from '@/components/CTable/CTable'
import IBulletinInsertOrUpdateForm from '@/model/form/bulletin/IBulletinInsertOrUpdateForm'
import IBulletinPageForm from '@/model/form/bulletin/IBulletinPageForm'
import IBulletinVO from '@/model/vo/bulletin/IBulletinVO'
import { execConfirm, onModalCancel, ToastSuccess } from '@/util/CommonUtil'
import { dateFormat } from '@/util/DateUtil'
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons'
import {
  Badge,
  Button,
  ButtonGroup,
  Dropdown,
  Form,
  Modal,
  Row,
  Space,
} from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import {
  Dispatch,
  MutableRefObject,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react'
import BulletinColumns from './BulletinColumns'
import BulletinFormItem, { getBulletinFormSelectData } from './BulletinFormItem'
import BulletinSearchFormItem, {
  getBulletinSearchFormSelectData,
} from './BulletinSearchFormItem'
import { IconTick, IconUndo } from '@douyinfe/semi-icons'
import { ChangeInfoSorter } from '@douyinfe/semi-ui/lib/es/table'
import { updateTimeOrder } from '@/util/http'

export default function Bulletin() {
  const [selectedRowKeyList, setSelectedRowKeyList] = useState<
    (string | number)[]
  >([]) // 表格选中的 key集合
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<IBulletinVO[]>([])
  const [initForm, setInitForm] = useState<IBulletinInsertOrUpdateForm>({}) // modal表单初始值
  const [modalTitle, setModalTitle] = useState('')
  const [modalVisible, setModalVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const [sideSheetVisible, setSideSheetVisible] = useState(false) // 搜索 sideSheet是否显示
  const [searchForm, setSearchForm] = useState<IBulletinPageForm>({}) // 搜索表单初始值

  const [total, setTotal] = useState(0)
  const [pageNum, setPageNum] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [sorter, setSorter] = useState<ChangeInfoSorter<any>>()

  const formApi = useRef<FormApi>()

  // 执行获取 table数据
  function doGetTableData() {
    getTableData(
      setDataSource,
      setLoading,
      searchForm,
      pageNum,
      pageSize,
      setTotal,
      sorter
    )
  }

  const { dictList } = getBulletinFormSelectData(modalVisible)
  const { userList } = getBulletinSearchFormSelectData(sideSheetVisible)

  useEffect(() => {
    doGetTableData()
  }, [])

  return (
    <div className="p-l-r-20">
      <CSearchForm
        sideSheetVisible={sideSheetVisible}
        setSideSheetVisible={setSideSheetVisible}
        getTableData={(values: any) => {
          setPageNum(1) // 这里的值不会立即生效
          setPageSize(10) // 这里的值不会立即生效
          getTableData(
            setDataSource,
            setLoading,
            values,
            1,
            10,
            setTotal,
            sorter
          )
        }}
        setSearchForm={setSearchForm}
        width={410}
      >
        <BulletinSearchFormItem
          dictList={dictList}
          userList={userList}
        ></BulletinSearchFormItem>
      </CSearchForm>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={() => {
          formApi.current?.submitForm()
        }}
        onCancel={() => {
          onModalCancel(setModalVisible, formApi.current, initForm)
        }}
        maskClosable={false}
        confirmLoading={confirmLoading}
      >
        <Form
          onSubmit={(form) => {
            if (confirmLoading) return
            modalSubmitClick(
              form,
              setConfirmLoading,
              setModalVisible,
              doGetTableData
            )
          }}
          disabled={confirmLoading}
          getFormApi={(api) => (formApi.current = api)}
          initValues={initForm}
        >
          <Row gutter={30}>
            <BulletinFormItem dictList={dictList} />
          </Row>
        </Form>
      </Modal>

      <div className="flex jc-sb m-t-b-10">
        <Space>
          <Button
            theme="solid"
            onClick={() => {
              const initFormTemp: IBulletinInsertOrUpdateForm = {}
              setInitForm(initFormTemp)
              setModalTitle('新增公告')
              setModalVisible(true)
            }}
          >
            新增
          </Button>
          <Button
            theme="solid"
            type="danger"
            onClick={() => {
              delData(selectedRowKeyList, setSelectedRowKeyList, doGetTableData)
            }}
          >
            删除
          </Button>
        </Space>

        {/* @ts-ignore */}
        <ButtonGroup>
          <Button
            onClick={() => {
              setSideSheetVisible(true)
            }}
            icon={
              <Badge dot={Object.keys(searchForm).length !== 0} type="warning">
                <IconSearch title="搜索" className="flex ai-c" />
              </Badge>
            }
          ></Button>
          <Button
            onClick={() => {
              if (!loading) {
                doGetTableData()
              }
            }}
            disabled={loading}
            icon={<IconRefresh spin={loading} title="刷新" />}
          ></Button>
        </ButtonGroup>
      </div>

      <CTable<IBulletinVO>
        onChange={({ sorter }) => {
          setSorter(sorter)
          getTableData(
            setDataSource,
            setLoading,
            searchForm,
            pageNum,
            pageSize,
            setTotal,
            sorter
          )
        }}
        columns={BulletinColumns(dictList)}
        dataSource={dataSource}
        loading={loading}
        selectedRowKeyList={selectedRowKeyList}
        setSelectedRowKeyList={setSelectedRowKeyList}
        pagination={{
          total,
          currentPage: pageNum,
          pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setPageNum(currentPage) // 这里的值不会立即生效
            setPageSize(pageSize) // 这里的值不会立即生效
            getTableData(
              setDataSource,
              setLoading,
              searchForm,
              currentPage,
              pageSize,
              setTotal,
              sorter
            )
          },
          showSizeChanger: true,
        }}
        defaultOperateClickFun={(text, record, index) => {
          record.status === 1
            ? editData(
                setInitForm,
                setModalTitle,
                setModalVisible,
                setConfirmLoading,
                record,
                formApi,
                confirmLoading
              )
            : undefined
        }}
        operateDropdownItem={(text, record, index) => (
          <>
            <Dropdown.Item
              disabled={record.status === 2}
              onClick={() => {
                editData(
                  setInitForm,
                  setModalTitle,
                  setModalVisible,
                  setConfirmLoading,
                  record,
                  formApi,
                  confirmLoading
                )
              }}
            >
              编辑
            </Dropdown.Item>
            <Dropdown.Item
              disabled={new Date(record.sendTime!) <= new Date()}
              icon={record.status === 1 ? <IconTick /> : <IconUndo />}
              onClick={() => {
                {
                  const uri =
                    record.status === 1
                      ? '/bulletin/submit'
                      : '/bulletin/revoke'
                  execConfirm(
                    () => {
                      return notBlankIdApi<string>(uri, {
                        id: record.id,
                      }).then(({ data }) => {
                        ToastSuccess(data.msg)
                        doGetTableData()
                      })
                    },
                    undefined,
                    `确定${record.status === 1 ? '发布' : '撤回'}【${
                      record.title
                    }】吗？`
                  )
                }
              }}
            >
              {record.status === 1 ? '发布' : '撤回'}
            </Dropdown.Item>
            <Dropdown.Item
              disabled={record.status === 2}
              className={record.status === 1 ? 'red' : ''}
              onClick={() => {
                delData(
                  selectedRowKeyList,
                  setSelectedRowKeyList,
                  doGetTableData,
                  record
                )
              }}
            >
              删除
            </Dropdown.Item>
          </>
        )}
      ></CTable>
    </div>
  )
}

// 编辑数据
function editData(
  setInitForm: Dispatch<SetStateAction<IBulletinInsertOrUpdateForm>>,
  setModalTitle: Dispatch<SetStateAction<string>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  record: IBulletinVO,
  formApi: MutableRefObject<FormApi<any> | undefined>,
  confirmLoading: boolean
) {
  if (confirmLoading) {
    return
  }
  setInitForm({ id: record.id }) // 重置 initForm的值
  setModalTitle('编辑公告')
  setModalVisible(true)
  setConfirmLoading(true)
  notBlankIdApi<IBulletinVO>('/bulletin/infoById', { id: record.id }).then(
    ({ data }) => {
      setInitForm(data.data)
      formApi.current?.setValues(data.data, { isOverride: true })
      setConfirmLoading(false)
    }
  )
}

// 获取 table数据
function getTableData(
  setDataSource: Dispatch<SetStateAction<IBulletinVO[]>>,
  setLoading: Dispatch<SetStateAction<boolean>>,
  searchForm: IBulletinPageForm,
  pageNum: number,
  pageSize: number,
  setTotal: Dispatch<SetStateAction<number>>,
  sorter: ChangeInfoSorter<any> | undefined
) {
  setLoading(true)
  bulletinPageApi({
    ...searchForm,
    stBeginTime:
      searchForm.sendTimeList && searchForm.sendTimeList.length
        ? dateFormat(searchForm.sendTimeList[0])
        : undefined,
    stEndTime:
      searchForm.sendTimeList && searchForm.sendTimeList.length
        ? dateFormat(searchForm.sendTimeList[1])
        : undefined,
    pageNum,
    pageSize,
    orderList: sorter?.sortOrder
      ? [{ name: sorter.dataIndex, value: sorter.sortOrder }, updateTimeOrder]
      : [updateTimeOrder],
  })
    .then(({ data }) => {
      setDataSource(data.data.records)
      setTotal(data.data.total)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}

// 删除数据
function delData(
  selectedRowKeyList: (string | number)[],
  setSelectedRowKeyList: Dispatch<SetStateAction<(string | number)[]>>,
  getTableData: () => void,
  record?: IBulletinVO
) {
  doDelDataClick(
    '/bulletin/deleteByIdSet',
    selectedRowKeyList,
    setSelectedRowKeyList,
    getTableData,
    record,
    record?.title
  )
}

// modal，表单提交事件
function modalSubmitClick(
  form: IBulletinInsertOrUpdateForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  doGetTableData: () => void
) {
  setConfirmLoading(true)

  form.sendTime = dateFormat(new Date(form.sendTime!))

  bulletinInsertOrUpdateApi(form)
    .then(({ data }) => {
      setModalVisible(false)
      setConfirmLoading(false)
      ToastSuccess(data.msg)
      doGetTableData() // 刷新table
    })
    .catch(() => {
      setConfirmLoading(false)
    })
}
